﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using System.Diagnostics;
using System.Windows.Input;
using System.Dynamic;
using System.ComponentModel;
using System.Reflection;
using System.Windows.Data;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using System.Windows.Interactivity;
using ViewMaker.Core.Utils;

namespace ViewMaker.Core.Silverlight
{
    public class SlContentControlView : IViewContent
    {
        private Control targetControl;

        public SlContentControlView(Control targetContent, ViewLayoutItem root)
        {
            this.targetControl = targetContent;
            this.targetControl.IsTabStop = false;

            var behavior = new ViewCommandBehavior { Helper = ServiceLocator.GetService<IViewCommandHelper>() };
            Interaction.GetBehaviors(targetControl).Add(behavior);
            SetConentControlInfo(root);

        }

        private void SetConentControlInfo(ViewLayoutItem root)
        {
            var winSettigs = root.Control.WindowSettings;
            if (winSettigs.FontSize.HasValue) targetControl.FontSize = winSettigs.FontSize.Value;
            if (!string.IsNullOrEmpty(winSettigs.Foreground)) targetControl.Foreground = SilverlightUtil.GetColor(winSettigs.Foreground);
            if (!string.IsNullOrEmpty(winSettigs.Background)) targetControl.Background = SilverlightUtil.GetColor(winSettigs.Background);
        }

        public object Content
        {
            get { return GetRootParent(targetControl); }
        }

        private FrameworkElement GetRootParent(FrameworkElement obj)
        {
            var fe = obj.Parent as FrameworkElement;
            if (fe == null) return obj;
            return GetRootParent(fe);
        }
    }
}
